package yams.resource.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import javafx.util.Callback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yams.callback.IdCallback;
import yams.common.InfoPage;
import yams.common.constants.BillStatusEnum;
import yams.common.constants.Constants;
import yams.common.exception.EntityNotFoundException;
import yams.domain.*;
import yams.resource.IBillResource;
import yams.resource.JsonCommonResource;
import yams.response.JsonResponse;
import yams.service.*;
import yams.utils.BreezeeUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.Date;
import java.util.TreeMap;

/**
 * 账单服务实现类
 * Created by Silence on 2017/5/2.
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/bill")
public class DefaultBillResource extends JsonCommonResource implements IBillResource {

    @Resource
    private IBillService billService;
    @Resource
    private IContractService contractService;
    @Resource
    private IHouseService houseService;
    @Resource
    private IUserService userService;
    @Resource
    private IWeChatService weChatService;
    @Autowired
    private IdCallback idCallback;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public JsonResponse<BillEntity> page(@RequestBody BillEntity billEntity) {
        //日期查找bug---格式化日期类型
        try {
            if (billEntity.getProperties().get("_startDate") != null && billEntity.getProperties().get("_startDate") !="") {
                billEntity.getProperties().put("payedDate_gt", BreezeeUtils.DATE_FORMAT_LONG.parse(billEntity.getProperties().get("_startDate").toString() + " 00:00:00"));
            }
            if (billEntity.getProperties().get("_endDate") != null && billEntity.getProperties().get("_endDate") != "") {
                billEntity.getProperties().put("payedDate_le", BreezeeUtils.DATE_FORMAT_LONG.parse(billEntity.getProperties().get("_endDate").toString() + " 23:59:59"));
            }
            if (billEntity.getProperties().get("_startDate_t") != null && billEntity.getProperties().get("_startDate_t") != "") {
                billEntity.getProperties().put("createdDate_gt", BreezeeUtils.DATE_FORMAT_LONG.parse(billEntity.getProperties().get("_startDate_t").toString() + " 00:00:00"));
            }
            if (billEntity.getProperties().get("_endDate_t") != null && billEntity.getProperties().get("_endDate_t") != "") {
                billEntity.getProperties().put("createdDate_le", BreezeeUtils.DATE_FORMAT_LONG.parse(billEntity.getProperties().get("_endDate_t").toString() + " 23:59:59"));
                System.out.println("----------------");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        JsonResponse<BillEntity> billEntityJsonResponse = _pageAll(billService, billEntity);
        for (BillEntity billEntity1:billEntityJsonResponse.getRows()) {
            HouseEntity houseEntity=houseService.findByCode(billEntity1.getHouse().getCode());
            UserEntity userEntity=userService.findById(houseEntity.getManager());
            if(userEntity!=null){
                billEntity1.getProperties().put("phone",userEntity.getPhone());
            }
            billEntity1.getProperties().put("house",houseEntity);

        }
        return billEntityJsonResponse;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @Override
    public JsonResponse<BillEntity> findById(@PathVariable String id) {
        return _findOne(billService, id, 0);
    }

    @RequestMapping(value = "/empty/{id}", method = RequestMethod.GET)
    @Override
    public JsonResponse<EmptyEntity> other(@PathVariable String id) {
        EmptyEntity emptyEntity=new EmptyEntity();
        BillEntity billEntity=billService.findById(id);
        UserEntity userEntity=userService.findById(billEntity.getUser().getId());
        emptyEntity.getProperties().put("user",userEntity);
        emptyEntity.getProperties().put("bill",billEntity);
        return JsonResponse.buildSingle(emptyEntity);
    }

    @RequestMapping(value = "/firstOrNot/{id}",method = RequestMethod.GET)
    @Override
    public InfoPage<BillEntity> findBillsCountByUserId(@PathVariable String id){
        BillEntity billEntity=new BillEntity();
        BillEntity billEntity1=billService.findById(id);
        billEntity.getProperties().put("user_id_obj_ae",billEntity1.getUser().getId());
        billEntity.getProperties().put("contract_id_obj_ae",billEntity1.getContract().getId());
        return billService.pageAll(billEntity);
    }

    @RequestMapping(value = "/code/{code}", method = RequestMethod.GET)
    @Override
    public JsonResponse<BillEntity> findByCode(@PathVariable String code) {
        return _findOne(billService, code, 1);
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @Override
    public JsonResponse<BillEntity> save(@RequestBody BillEntity billEntity) {
        return _saveInfo(billService, billEntity);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @Override
    public JsonResponse<BillEntity> delete(@PathVariable String id) {
        return _delete(billService, id);
    }

    /**
     * 支付账单，更新账单信息
     * @param bill
     * @return
     */
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    @Override
    public JsonResponse<BillEntity> payBill(@RequestBody BillEntity bill) {
        try {
            BillEntity old = billService.findById(bill.getId());
            old.setStatus(1);
            old.setPayedAmount(bill.getPayedAmount());
            old.setPayedDate(new Date());
            old.setPayMethod(bill.getPayMethod());
            old.setPayedPerson(bill.getPayedPerson());
            //payBill方法仅仅保存实体，没有其它作用
            billService.payBill(old);
        } catch (EntityNotFoundException e) {
            e.printStackTrace();
        }
        return JsonResponse.OK();
    }

    /**
     * 保存新建临时账单
     * @param bill
     * @return
     */
    @RequestMapping(value = "/addTempBill", method = RequestMethod.PUT)
    @Override
    public JsonResponse<BillEntity> addBill(@RequestBody BillEntity bill) {
       //通过房间信息，来获得合同
        LocalDate ld = LocalDate.now();
        HouseEntity houseEntity=houseService.findById(bill.getHouse().getId());
        ContractEntity contractEntity = contractService.findById(houseEntity.getContract().getId());
        UserEntity user = contractEntity.getUser();
        UserEntity manager = userService.findById(houseEntity.getManager());
        bill.setCode("2" + contractEntity.getCode() + "-" + ld.toString().replace("-", ""));
        bill.setName(contractEntity.getHouseName() + ld.toString() + bill.getType());
        bill.setCreatedDate(new Date());
        bill.setRemark(bill.getRemark());
        bill.setTotalAmount(bill.getTotalAmount());
        bill.setStatus(BillStatusEnum.UNPAID.getValue());
        billService.getRepository().saveEntity(bill, new Callback[]{idCallback});

        //给客户发送账单消息
        WechatTemplateMsg templateMsg = new WechatTemplateMsg();
        templateMsg.setTouser(user.getWeChat());
        templateMsg.setTemplate_id("8TBpNPfFKp8OEOVQqXHsPEcXHUvQuGjTZa9HKQuePqM");
        templateMsg.setUrl("http://"+ Constants.WECHAT_URL+"/yams/view/account?openId=" + user.getWeChat());
        TreeMap<String, TreeMap<String, String>> map = Maps.newTreeMap();
        map.put("first", templateMsg.item("尊敬的客户，您好！您的临时账单已出，请在12小时内完成支付", "#173177"));
        map.put("remark", templateMsg.item("若有疑问请与管理员(" + manager.getName() + "," + manager.getPhone() + ")联系", "#173177"));
        templateMsg.setData(map);
        String jsonTempl = JSONObject.toJSONString(templateMsg);

        try {
            weChatService.sendTemplate(jsonTempl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JsonResponse.OK();
    }
}
